package com.haust.aliyunoos.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haust.aliyunoos.config.OssUtils;
import com.haust.aliyunoos.mapper.UserMapper;
import com.haust.aliyunoos.pojo.User;
import com.haust.aliyunoos.service.FileUploadService;
import com.haust.aliyunoos.utils.OSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: csp1999
 * @Date: 2020/10/31/16:40
 * @Description: OSS 文件上传controller
 */
@Api(description = "阿里云OSS文件上传、下载、删除API")
@RequestMapping("api/pri/file")
@RestController
public class OssFileController {

    @Autowired
    private OSS ossClient;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;


    /**
     * 上传视频
     */
    @ApiOperation(value = "视频上传")
    @PostMapping("/uploadVideo")
    @CrossOrigin(origins = "*", maxAge = 3600)//跨域
    public Map<String, Object> uploadVideo(@RequestParam("imgFile") MultipartFile imgFile, String hId,String hVr, HttpServletRequest req) throws Exception {
        OSSUtil ossClient = new OSSUtil();
        Map<String, Object> m = new HashMap<>();
        if (imgFile.isEmpty()) {
            m.put("error", "上传文件不能为空");
        }
        String newsUrl = "";
        if (!((MultipartFile) imgFile).isEmpty()) {
            try {
                //将文件上传
                String name = ossClient.uploadVideo(imgFile);
                //获取文件的URl地址  以便前台  显示
                String imgUrl = ossClient.getImgUrl(name);
                m.put("url", imgUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            m.put("error", "上传图片不可为空");
        }
        return m;
    }


    /*
     * 文件上传api
     * @param: file
     * @return: com.alibaba.fastjson.JSONObject
     * @create: 2020/10/31 17:35
     * @author: csp1999
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("upload")
    public JSONObject upload(@RequestParam("file") MultipartFile file) {
        JSONObject jsonObject = new JSONObject();
        if (file != null) {
            String returnFileUrl = fileUploadService.upload(file);
            if (returnFileUrl.equals("error")) {
                jsonObject.put("error", "文件上传失败！");
                return jsonObject;
            }
            jsonObject.put("success", "文件上传成功！");
            jsonObject.put("returnFileUrl", returnFileUrl);
            return jsonObject;
        } else {
            jsonObject.put("error", "文件上传失败！");
            return jsonObject;
        }
    }



    @ApiOperation(value = "文件测试user")
    @PostMapping(value = "/user")
    public JSONObject showUser(@RequestBody User user ) throws Exception {
        String resourceUrl = user.getResourceUrl();
        String result=resourceUrl.substring(resourceUrl.indexOf("lzh"));
        user.setResourceUrl(result);
        user.setId("123");
        System.out.println(user);
        userMapper.insert(user);
       return null;
    }

    /*
     * 文件下载api
     * @param: fileName
     * @param: response
     * @return: com.alibaba.fastjson.JSONObject
     * @create: 2020/10/31 17:35
     * @author: csp1999
     */
    @ApiOperation(value = "文件下载")
    @GetMapping(value = "download/{fileName}")
    public JSONObject download(@PathVariable("fileName") String fileName, HttpServletResponse response) throws Exception {
        JSONObject jsonObject = new JSONObject();

        String status = fileUploadService.download(fileName, response);
        if (status.equals("error")) {
            jsonObject.put("error", "文件下载失败！");
            return jsonObject;
        } else {
            jsonObject.put("success", "文件下载成功！");
            return jsonObject;
        }
    }

    /*
     * 文件删除api
     * @param: fileName
     * @return: com.alibaba.fastjson.JSONObject
     * @create: 2020/10/31 17:35
     * @author: csp1999
     */
    @ApiOperation(value = "文件删除")
    @GetMapping("/delete/{fileName}")
    public JSONObject DeleteFile(@PathVariable("fileName") String fileName) {
        JSONObject jsonObject = new JSONObject();

        String status = fileUploadService.delete(fileName);
        if (status.equals("error")) {
            jsonObject.put("error", "文件删除失败！");
            return jsonObject;
        } else {
            jsonObject.put("success", "文件删除成功！");
            return jsonObject;
        }
    }

    @ApiOperation(value = "getUrl")
    @GetMapping("/getUrl/{key}")
    public String getUrl(@PathVariable("key") String key){

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id","12345");
        List<User> users = userMapper.selectList(userQueryWrapper);
        String resourceUrl = users.get(0).getResourceUrl();
        key=resourceUrl;


        Date expiration = new Date(new Date().getTime() + Long.parseLong("100000"));
        URL url = ossClient.generatePresignedUrl("jinmao-common", key, expiration);
        return url.toString();
    }

    @ApiOperation(value = "获取key")
    @GetMapping("/getKey")
    public String getKey(String id){

        if(StringUtils.isEmpty(id)){
            return null;
        }
        String[] split = id.split("-");

        ObjectListing objectListing = ossClient.listObjects("jinmao-common","ucms");
        Map<String,String> map = new HashMap<>();
        List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
        for (OSSObjectSummary objectSummary : objectSummaries) {
            stringRedisTemplate.opsForValue().append(objectSummary.getETag(),objectSummary.getKey());
        }
        OssUtils ossUtils = new OssUtils();
        String url = ossUtils.getUrl(map.get(id));
        return url;
    }

    //@PostConstruct
    public void init(){

       // ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest("jinmao-common").withPrefix("ucms").withMaxKeys(1000));
        //n;ew ListObjectsRequest("jinmao-common").withMarker("ucms").withMaxKeys(1000)
      //  new ListObjectsRequest("jinmao-common").withPrefix("ucms").withKey()
       // new ListObjectsRequest("jinmao-common").withMarker("ucms").withMaxKeys(1000);
       // ObjectListing objectListing = ossClient.listObjects("jinmao-common","ucms");
       // OSSObject object = ossClient.getObject("jinmao-common", "36C6D9FE3EF0923884CA53DDC3BEF440");
      //  List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
      //  List<String> arrayList = new ArrayList<>();
      //  for (OSSObjectSummary objectSummary : objectSummaries) {
       //     arrayList.add(objectSummary.getETag());
           // stringRedisTemplate.opsForValue().set(objectSummary.getETag(),objectSummary.getKey());
      //  }
      //  boolean contains = arrayList.contains("5B73A28C605EF48AD73A3C0EE84440B9");
      //  System.out.println(contains);

        String nextMarker = null;
        ObjectListing objListing;
        List<String> strings = new ArrayList<>();
        int size=0;
        do
        {

            if (nextMarker == null) // 第一次的分页
                objListing = ossClient.listObjects(new ListObjectsRequest("jinmao-common").withPrefix("ucms").withMaxKeys(200));
            else // 以后的分页，附带nextMarker
                objListing = ossClient.listObjects(
                        new ListObjectsRequest("jinmao-common").withPrefix("ucms").withMarker(nextMarker).withMaxKeys(200));

            List<OSSObjectSummary> objectSummaries = objListing.getObjectSummaries();
            for (OSSObjectSummary objectSummary : objectSummaries)
            {
               // stringRedisTemplate.opsForValue().set(objectSummary.getETag(), objectSummary.getKey(),300,TimeUnit.SECONDS);
                strings.add(objectSummary.getETag());
            }
            // 下一次分页的nextMarker
            nextMarker = objListing.getNextMarker();
            size=objectSummaries.size();
        } while (size==200);
        System.out.println(strings.size());

        PutObjectResult putObjectResult = ossClient.putObject("", "", (File) null);

        //putObjectResult.get

       /* List<String> abc = new ArrayList<>();


      String nextMarker = null;
        ObjectListing objListing;
        int size=0;
        do
        {

            if (nextMarker == null) // 第一次的分页
                objListing = ossClient.listObjects(new ListObjectsRequest("jinmao-common").withPrefix("ucms").withMaxKeys(1000));
            else // 以后的分页，附带nextMarker
                objListing = ossClient.listObjects(
                        new ListObjectsRequest("jinmao-common").withPrefix("ucms").withMarker(nextMarker).withMaxKeys(100));

            List<OSSObjectSummary> sums = objListing.getObjectSummaries();
            for (OSSObjectSummary s : sums)
            {
                String ossKey = s.getKey();
                abc.add(ossKey);
            }
            // 下一次分页的nextMarker
            nextMarker = objListing.getNextMarker();
            size=sums.size();
        } while (size==100);
        System.out.println(abc);*/
    }

}
